import {
  Button,
  Cascader,
  Col,
  Form,
  Input,
  message,
  Row,
  Select,
  Space,
  Upload,
} from "antd";
import React, { useState } from "react";
import TextArea from "antd/lib/input/TextArea";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons/lib/icons";
import axios from "axios";
import { v4 as uuidv4 } from "uuid";

import {
  CREATE_PRODUCT,
  HAS_PRODUCT_EXIST,
  IMAGE,
  UPLOAD_PRODUCT,
} from "../../../../constants/api-constants";
import dateFnsGenerateConfig from "rc-picker/es/generate/dateFns";
import generatePicker from "antd/es/date-picker/generatePicker";
import "antd/es/date-picker/style/index";
import provice from "../../../../util/place";
import { useBoolean, useRequest } from "ahooks";
import { UploadFile, UploadFileStatus } from "antd/lib/upload/interface";
import { DELETE_IMAGE } from "./../../../../constants/api-constants";
// const fs = require("fs");
const DatePicker = generatePicker<Date>(dateFnsGenerateConfig);

const { Option } = Select;

interface detailProps {
  record?: ProjectList.item;
  setDetailFalse: Function;
  getList: Function;
  loading: boolean;
  setLoading: Function;
}

const options = provice;
export default (props: detailProps) => {
  const { record, setDetailFalse, getList, loading } = props;
  const [submitLoading, { setFalse, setTrue }] = useBoolean(false);
  const [errors, setErrors] = useState("");
  const [pictureList, setPictureList] = useState<UploadFile[]>([]);
  const header = { authorization: localStorage.getItem("Authorization") ?? "" };

  const handleBeforeUpload = (file: { type: string; size: number }) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("只支持JPG/PNG格式的图片!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片必须小于2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange = (info: any) => {
    const { file } = info;
    if (file.status === "done") {
      message.success(`${info.file.name} 上传成功`);

      const newPicture = {
        name: `${info.file.response.mainData.url}`,
        status: "done" as UploadFileStatus,
        url: `${IMAGE}/?filename=${info.file.response.mainData.url}`,
        uid: uuidv4(),
      };

      setPictureList((list) => [...list, newPicture]);
    } else if (info.file.status === "error") {
      message.error(`${info.file.name} 上传失败.`);
    }
  };

  const { run: deletePicture } = useRequest(
    (filename: string, databaseName?: string) => ({
      url: DELETE_IMAGE,
      method: "DELETE",
      data: {
        filename,
        databaseName,
      },
    }),
    {
      manual: true,
    }
  );

  const handleRemove = (info: any) => {
    console.log(info);
    let pictureName: any;
    if (info.response) {
      pictureName = info.response.mainData.url;
      deletePicture(`${pictureName}`);
    } else {
      const pictures = info.url.split("=");
      console.log(pictures);
      pictureName = pictures[1];
      deletePicture(`${pictureName}`, `${info.url}`);
    }

    const newList = pictureList.filter((pic) => {
      return pic.name !== `${pictureName}`;
    });
    setPictureList(newList);
  };

  if (!record) {
    return <></>;
  }
  const hasErr = !!errors;
  let filters = {};
  if (record && record.defValue) {
    // const patent = record.defValue.patents?.map((v: any, _i: number) => {
    //   return v.uuid;
    // });
    console.log(record);
    let address = "";
    let addressBefore = [];

    if (record && record.defValue && record.defValue.address) {
      const addAll = record.defValue.address?.split(";");
      address = addAll.pop() ?? "";
      addressBefore = addAll;
    }
    filters = {
      name: record.name ? record.name : "",
      patent: record.patent ? record.patent : "",
      registrationStatus: record.registrationStatus
        ? record.registrationStatus
        : "",
      model: record.model ? record.model : "",
      productNo: record.productNo ? record.productNo : "",
      application_area: record.defValue.application_area?.uuid
        ? record.defValue.application_area?.uuid
        : "",
      organizations: record.defValue.organizations
        ? record.defValue.organizations.map((v: { uuid: string }) => {
            return v.uuid;
          })
        : [],
      address: address ?? "",
      addressBefore,
      // patent,
      contactPerson: record.defValue.contactPerson
        ? record.defValue.contactPerson
        : "",
      contactTel: record.defValue.contactTel ? record.defValue.contactTel : "",
      contactEmail: record.defValue.contactEmail
        ? record.defValue.contactEmail
        : "",
      description: record.defValue.description
        ? record.defValue.description
        : "",
      updateTime: record.defValue.updateTime
        ? new Date(record.defValue.updateTime)
        : "",
      filler: record.defValue.filler ? record.defValue.filler : "",
      file: new File([], "null.xlsx"),
      company: record.defValue.unit ?? "",
    };
  } else {
    filters = {
      updateTime: new Date(),
      filler: localStorage.getItem("userName"),
    };
  }
  return (
    <Form
      onValuesChange={(changedValues, allValues) => {
        const len = Object.keys(changedValues).filter((v) => {
          return !(v === "name" || v === "model" || v === "company");
        }).length;
        console.log(changedValues);
        if (
          len === 0 &&
          allValues.name &&
          allValues.model &&
          allValues.company
        ) {
          axios
            .post(HAS_PRODUCT_EXIST, {
              name: allValues.name,
              model: allValues.model,
              unit: allValues.company,
            })
            .then((_r) => {
              setErrors("");
            })
            .catch((r) => {
              console.log(r);
              const { msg } = r.response.data;
              setErrors(msg);
            });
        }
      }}
      initialValues={filters}
      onFinish={(e) => {
        // const formData = new FormData();
        let productNo;
        let productId;
        const addressBefore = e.addressBefore
          ? e.addressBefore.join(";") + ";"
          : "";
        if (record.defValue) {
          productId = record.defValue.id;
          productNo = record.defValue.uuid;
          // formData.append("id", record.defValue.id);
          // formData.append("productNo", record.defValue.uuid);
        } else {
          productNo = uuidv4();
          // formData.append("productNo", uuidv4());
        }
        // formData.append("name", e.name);

        // formData.append("registrationStatus", e.registrationStatus);
        // formData.append("model", e.model);
        // formData.append("application_area", e.application_area);
        // formData.append("organization", e.organizations);
        // formData.append("address", addressBefore + e.address);
        // formData.append("patent", e.patent);
        // formData.append("contactPerson", e.contactPerson);
        // formData.append("contactEmail", e.contactEmail);
        // formData.append("contactTel", e.contactTel);
        // formData.append("description", e.description);
        // formData.append("updateTime", e.updateTime);
        // formData.append("filler", e.filler);
        // formData.append("company", e.company);

        // formData.append("file", e.file.file ?? new File([], "null.xlsx"));
        // console.log(formData);

        let pictureUrls;
        if (pictureList) {
          pictureUrls = pictureList.map((picture) => {
            return picture.url;
          });
        }

        setTrue();

        if (record.defValue) {
          axios
            .post(UPLOAD_PRODUCT, {
              productNo,
              productId,
              name: e.name,
              registrationStatus: e.registrationStatus,
              model: e.model,
              application_area: e.application_area,
              organization: e.organizations,
              address: addressBefore + e.address,
              patent: e.patent,
              contactPerson: e.contactPerson,
              contactEmail: e.contactEmail,
              contactTel: e.contactTel,
              description: e.description,
              updateTime: e.updateTime,
              filler: e.filler,
              company: e.company,
              pictureUrls,
            })
            .then((_r) => {
              setFalse();

              getList();

              setDetailFalse();
            })
            .catch((e) => {
              setFalse();

              getList();
              setDetailFalse();
            });
        } else {
          axios
            .post(
              CREATE_PRODUCT,
              {
                productNo,
                productId,
                name: e.name,
                registrationStatus: e.registrationStatus,
                model: e.model,
                application_area: e.application_area,
                organization: e.organizations,
                address: addressBefore + e.address,
                patent: e.patent,
                contactPerson: e.contactPerson,
                contactEmail: e.contactEmail,
                contactTel: e.contactTel,
                description: e.description,
                updateTime: e.updateTime,
                filler: e.filler,
                company: e.company,
                pictureUrls,
              },
              { timeout: 50000 }
            )
            .then((_r) => {
              setFalse();

              getList();

              setDetailFalse();
            })
            .catch((e) => {
              setFalse();
              message.error("成果编号重复或服务器异常请重试");
            });
        }
      }}
      layout="horizontal"
      title="机构信息"
    >
      <Row justify="space-between">
        <Col span={11}>
          <Form.Item
            rules={[{ required: true, message: "成果名称不能为空" }]}
            name="name"
            label="成果名称 "
            validateStatus={hasErr ? "error" : "success"}
            help={errors}
            labelAlign="right"
          >
            <Input />
          </Form.Item>
        </Col>
        <Col span={11}>
          <Form.Item
            rules={[{ required: true, message: "成果型号不能为空" }]}
            name="model"
            validateStatus={hasErr ? "error" : "success"}
            help={errors}
            label="成果型号"
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Form.Item
            name="company"
            label="所属单位 "
            rules={[{ required: true, message: "所属单位不能为空" }]}
          >
            <Input
              placeholder={"请输入所属单位,多个用英文;分割。如：公司A;公司B"}
            />
          </Form.Item>
        </Col>
      </Row>
      <Row justify="space-between">
        <Col span={9}>
          <Form.Item name="organizations" label="投资机构">
            <Select mode="multiple">
              {record.organizationw?.map(
                (v: { name: string; uuid: string }) => {
                  return (
                    <Option key={v.uuid} value={v.uuid}>
                      {v.name}
                    </Option>
                  );
                }
              )}
            </Select>
          </Form.Item>
        </Col>
        <Col span={7}>
          <Form.Item name="addressBefore" label="选择城市" labelAlign="right">
            <Cascader options={options} placeholder="请输入成果所在的城市" />
          </Form.Item>
        </Col>
        <Col span={7}>
          <Form.Item name="address" label="具体街道" labelAlign="right">
            <Input />
          </Form.Item>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Form.Item
            name="patent"
            label="所用专利 "
            labelAlign="right"
            style={{ width: "100wh" }}
          >
            {/* <Select mode="tags">
              {record.patents?.map((v: { name: string; uuid: string }) => {
                return (
                  <Option key={v.uuid} value={v.uuid}>
                    {v.name}
                  </Option>
                );
              })}
            </Select> */}
            <Input
              // FIXME: 这里只是把select改成了input，逻辑没有改，这个字段对应 type.d.ts 中的 patent 属性
              placeholder={"请输入所用专利,多个用英文;分割。如：专利A;专利B"}
            />
          </Form.Item>
        </Col>
      </Row>
      <Row justify="space-between">
        <Col span={11}>
          <Form.Item
            rules={[{ required: true, message: "注册情况不能为空" }]}
            name="registrationStatus"
            label="医疗器械注册情况"
          >
            <Select>
              <Option value={"已注册"}>已注册</Option>
              <Option value={"未注册"}>未注册</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={11}>
          <Form.Item
            name="application_area"
            label="应用领域 "
            labelAlign="right"
            rules={[{ required: true, message: "应用领域不能为空" }]}
          >
            <Select>
              {record.application_areas.map(
                (v: { name: string; uuid: string }) => {
                  return (
                    <Option key={v.uuid} value={v.uuid}>
                      {v.name}
                    </Option>
                  );
                }
              )}
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Row justify="space-between">
        <Col span={7}>
          <Form.Item name="contactPerson" label="联系人姓名" labelAlign="right">
            <Input />
          </Form.Item>
        </Col>
        <Col span={7}>
          <Form.Item
            rules={[
              {
                pattern: /^1[3456789]\d{9}$/,
                message: "请输入正确的电话格式",
              },
            ]}
            name="contactTel"
            label="电话   "
            labelAlign="right"
          >
            <Input />
          </Form.Item>
        </Col>
        <Col span={7}>
          <Form.Item
            rules={[
              {
                type: "email",
                message: "请输入正确的邮箱格式",
              },
            ]}
            name="contactEmail"
            label="E-Mail"
            labelAlign="right"
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        rules={[
          { required: true, message: "成果简介不能为空,并且保证长度小于300" },
        ]}
        name="description"
        label="成果简介"
      >
        <TextArea
          style={{ resize: "none" }}
          maxLength={300}
          placeholder="成果简介（限制在300字之内）"
        />
      </Form.Item>

      {/* <Form.Item
        rules={[{ required: !record?.defValue, message: "请上传文件后再提交" }]}
        name="file"
        label="附件材料"
        labelAlign="right"
      >
        <Upload
          name="logo"
          beforeUpload={() => {
            return false;
          }}
          maxCount={1}
          accept={".pdf"}
        >
          <Button icon={<UploadOutlined />} type="primary">
            添加附件（PDF格式）
          </Button>
        </Upload>
      </Form.Item> */}
      <Form.Item name="picture" label="轮播图片" labelAlign="right">
        <Upload
          name="avatar"
          headers={header}
          action={IMAGE}
          maxCount={10}
          listType="picture-card"
          defaultFileList={record.images}
          beforeUpload={handleBeforeUpload}
          onChange={handleChange}
          onRemove={handleRemove}
        >
          {pictureList !== undefined && pictureList.length >= 10 ? null : (
            <div>
              {loading ? <LoadingOutlined /> : <PlusOutlined />}
              <div style={{ marginTop: 8 }}>图片上传</div>
            </div>
          )}
        </Upload>
      </Form.Item>
      {/* {record?.defValue ? (
        <Form.Item name="getFile" label="附件材料" labelAlign="right">
          <Button
            loading={loading}
            onClick={() => {
              setLoading(true);
              axios
                .post(PRODUCT_FILE_EXIST, { id: record?.defValue?.id })
                .then((r) => {
                  const { msg } = r.data;
                  message.success(msg);

                  window.location.href =
                    GET_PRODUCT_FILE + `?id=${record?.defValue?.id}`;

                  setLoading(false);
                })
                .catch((e) => {
                  setLoading(false);
                });
            }}
            icon={<CloudDownloadOutlined />}
            type="primary"
          >
            下载已有附件
          </Button>
        </Form.Item>
      ) : (
        <></>
      )} */}

      <Row>
        <Col span={6}>
          <Form.Item
            rules={[{ required: true, message: "录入时间不能为空" }]}
            name="updateTime"
            label="录入时间"
            labelAlign="right"
          >
            <DatePicker picker={"date"} disabled />
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item
            rules={[{ required: true, message: "填写人不能为空" }]}
            name="filler"
            label="填写人"
            labelAlign="right"
          >
            <Input readOnly />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item>
        <Space style={{ float: "right" }}>
          <Button loading={submitLoading} type="primary" htmlType="submit">
            提交
          </Button>
          <Button
            key="back"
            onClick={() => {
              setDetailFalse();
            }}
          >
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};
